<template>
  <div class="map-editor">
    <div class="editor-header">
      <div class="header-left">
        <h3>
          <el-icon><MapLocation /></el-icon>
          地图编辑器
        </h3>
        <el-button-group>
          <el-button 
            :type="currentTool === 'select' ? 'primary' : 'default'"
            @click="setTool('select')"
          >
            <el-icon><Pointer /></el-icon>
            选择
          </el-button>
          <el-button 
            :type="currentTool === 'room' ? 'primary' : 'default'"
            @click="setTool('room')"
          >
            <el-icon><Grid /></el-icon>
            房间
          </el-button>
          <el-button 
            :type="currentTool === 'npc' ? 'primary' : 'default'"
            @click="setTool('npc')"
          >
            <el-icon><User /></el-icon>
            NPC
          </el-button>
          <el-button 
            :type="currentTool === 'item' ? 'primary' : 'default'"
            @click="setTool('item')"
          >
            <el-icon><Box /></el-icon>
            物品
          </el-button>
          <el-button 
            :type="currentTool === 'fog' ? 'primary' : 'default'"
            @click="setTool('fog')"
          >
            <el-icon><Cloudy /></el-icon>
            迷雾
          </el-button>
        </el-button-group>
      </div>
      
      <div class="header-right">
        <el-button @click="clearMap">清空地图</el-button>
        <el-button type="primary" @click="saveMap">保存地图</el-button>
      </div>
    </div>

    <div class="editor-content">
      <!-- 地图画布 -->
      <div class="map-container">
        <div id="map" ref="mapContainer" class="map-canvas"></div>
        
        <!-- 地图工具栏 -->
        <div class="map-toolbar">
          <el-button-group>
            <el-button size="small" @click="zoomIn">
              <el-icon><ZoomIn /></el-icon>
            </el-button>
            <el-button size="small" @click="zoomOut">
              <el-icon><ZoomOut /></el-icon>
            </el-button>
            <el-button size="small" @click="resetView">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 属性面板 -->
      <div class="properties-panel">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <span>属性面板</span>
            </div>
          </template>
          
          <div v-if="selectedElement" class="element-properties">
            <h4>{{ getElementTypeName(selectedElement.type) }}</h4>
            
            <el-form :model="selectedElement" label-width="80px" size="small">
              <el-form-item label="名称">
                <el-input v-model="selectedElement.name" placeholder="请输入名称" />
              </el-form-item>
              
              <el-form-item label="描述">
                <el-input 
                  v-model="selectedElement.description" 
                  type="textarea" 
                  placeholder="请输入描述"
                  :rows="3"
                />
              </el-form-item>
              
              <el-form-item v-if="selectedElement.type === 'room'" label="房间类型">
                <el-select v-model="selectedElement.roomType" placeholder="选择房间类型">
                  <el-option label="普通房间" value="normal" />
                  <el-option label="重要房间" value="important" />
                  <el-option label="隐藏房间" value="hidden" />
                </el-select>
              </el-form-item>
              
              <el-form-item v-if="selectedElement.type === 'npc'" label="NPC类型">
                <el-select v-model="selectedElement.npcType" placeholder="选择NPC类型">
                  <el-option label="友好" value="friendly" />
                  <el-option label="中立" value="neutral" />
                  <el-option label="敌对" value="hostile" />
                </el-select>
              </el-form-item>
              
              <el-form-item v-if="selectedElement.type === 'item'" label="物品类型">
                <el-select v-model="selectedElement.itemType" placeholder="选择物品类型">
                  <el-option label="武器" value="weapon" />
                  <el-option label="道具" value="tool" />
                  <el-option label="线索" value="clue" />
                  <el-option label="宝藏" value="treasure" />
                </el-select>
              </el-form-item>
              
              <el-form-item>
                <el-button type="danger" size="small" @click="deleteElement">删除</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <div v-else class="no-selection">
            <p>选择一个地图元素来编辑属性</p>
          </div>
        </el-card>

        <!-- 图层控制 -->
        <el-card shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <el-icon><Layers /></el-icon>
              <span>图层控制</span>
            </div>
          </template>
          
          <div class="layer-controls">
            <el-checkbox v-model="showRooms" @change="toggleLayer('rooms')">房间</el-checkbox>
            <el-checkbox v-model="showNPCs" @change="toggleLayer('npcs')">NPC</el-checkbox>
            <el-checkbox v-model="showItems" @change="toggleLayer('items')">物品</el-checkbox>
            <el-checkbox v-model="showFog" @change="toggleLayer('fog')">迷雾</el-checkbox>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { useGameStore } from '@/stores/game'
import { ElMessage } from 'element-plus'

const gameStore = useGameStore()

// 响应式数据
const mapContainer = ref(null)
const map = ref(null)
const currentTool = ref('select')
const selectedElement = ref(null)
const showRooms = ref(true)
const showNPCs = ref(true)
const showItems = ref(true)
const showFog = ref(true)

// 地图元素
const mapElements = ref({
  rooms: [],
  npcs: [],
  items: [],
  fog: []
})

// 地图图层
const layers = ref({
  rooms: null,
  npcs: null,
  items: null,
  fog: null
})

// 绘制状态
const isDrawing = ref(false)
const currentPolygon = ref(null)
const currentMarker = ref(null)

// 方法
const initMap = () => {
  // 创建地图
  map.value = L.map('map', {
    center: [0, 0],
    zoom: 2,
    minZoom: 1,
    maxZoom: 10
  })

  // 添加瓦片图层
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map.value)

  // 创建图层组
  layers.value.rooms = L.layerGroup().addTo(map.value)
  layers.value.npcs = L.layerGroup().addTo(map.value)
  layers.value.items = L.layerGroup().addTo(map.value)
  layers.value.fog = L.layerGroup().addTo(map.value)

  // 绑定地图事件
  map.value.on('click', handleMapClick)
  map.value.on('mousemove', handleMapMouseMove)
}

const setTool = (tool) => {
  currentTool.value = tool
  selectedElement.value = null
}

const handleMapClick = (e) => {
  if (currentTool.value === 'select') return

  const latlng = e.latlng

  switch (currentTool.value) {
    case 'room':
      startDrawingRoom(latlng)
      break
    case 'npc':
      createNPC(latlng)
      break
    case 'item':
      createItem(latlng)
      break
    case 'fog':
      createFogArea(latlng)
      break
  }
}

const handleMapMouseMove = (e) => {
  if (currentTool.value === 'room' && isDrawing.value) {
    updateRoomDrawing(e.latlng)
  }
}

const startDrawingRoom = (latlng) => {
  isDrawing.value = true
  currentPolygon.value = L.polygon([latlng], {
    color: '#3388ff',
    fillColor: '#3388ff',
    fillOpacity: 0.2,
    weight: 2
  }).addTo(layers.value.rooms)

  // 绑定右键结束绘制
  map.value.on('contextmenu', finishDrawingRoom)
}

const updateRoomDrawing = (latlng) => {
  if (currentPolygon.value) {
    const latlngs = currentPolygon.value.getLatLngs()[0]
    latlngs.push(latlng)
    currentPolygon.value.setLatLngs(latlngs)
  }
}

const finishDrawingRoom = () => {
  if (currentPolygon.value) {
    isDrawing.value = false
    
    // 创建房间对象
    const room = {
      id: Date.now(),
      type: 'room',
      name: '新房间',
      description: '',
      roomType: 'normal',
      polygon: currentPolygon.value,
      latlngs: currentPolygon.value.getLatLngs()[0]
    }
    
    mapElements.value.rooms.push(room)
    
    // 绑定点击事件
    currentPolygon.value.on('click', () => selectElement(room))
    
    currentPolygon.value = null
    map.value.off('contextmenu', finishDrawingRoom)
  }
}

const createNPC = (latlng) => {
  const marker = L.marker(latlng, {
    icon: L.divIcon({
      className: 'npc-marker',
      html: '👤',
      iconSize: [30, 30]
    })
  }).addTo(layers.value.npcs)

  const npc = {
    id: Date.now(),
    type: 'npc',
    name: '新NPC',
    description: '',
    npcType: 'neutral',
    marker: marker,
    latlng: latlng
  }

  mapElements.value.npcs.push(npc)
  marker.on('click', () => selectElement(npc))
}

const createItem = (latlng) => {
  const marker = L.marker(latlng, {
    icon: L.divIcon({
      className: 'item-marker',
      html: '📦',
      iconSize: [25, 25]
    })
  }).addTo(layers.value.items)

  const item = {
    id: Date.now(),
    type: 'item',
    name: '新物品',
    description: '',
    itemType: 'tool',
    marker: marker,
    latlng: latlng
  }

  mapElements.value.items.push(item)
  marker.on('click', () => selectElement(item))
}

const createFogArea = (latlng) => {
  const circle = L.circle(latlng, {
    radius: 50,
    color: '#666',
    fillColor: '#666',
    fillOpacity: 0.5,
    weight: 2
  }).addTo(layers.value.fog)

  const fog = {
    id: Date.now(),
    type: 'fog',
    name: '迷雾区域',
    description: '',
    circle: circle,
    latlng: latlng,
    radius: 50
  }

  mapElements.value.fog.push(fog)
  circle.on('click', () => selectElement(fog))
}

const selectElement = (element) => {
  selectedElement.value = { ...element }
  currentTool.value = 'select'
}

const deleteElement = () => {
  if (!selectedElement.value) return

  const element = selectedElement.value
  const type = element.type

  // 从地图上移除
  if (element.polygon) {
    layers.value[type + 's'].removeLayer(element.polygon)
  }
  if (element.marker) {
    layers.value[type + 's'].removeLayer(element.marker)
  }
  if (element.circle) {
    layers.value[type + 's'].removeLayer(element.circle)
  }

  // 从数组中移除
  const index = mapElements.value[type + 's'].findIndex(item => item.id === element.id)
  if (index > -1) {
    mapElements.value[type + 's'].splice(index, 1)
  }

  selectedElement.value = null
  ElMessage.success('元素已删除')
}

const getElementTypeName = (type) => {
  const typeNames = {
    room: '房间',
    npc: 'NPC',
    item: '物品',
    fog: '迷雾区域'
  }
  return typeNames[type] || type
}

const toggleLayer = (layerName) => {
  if (layers.value[layerName]) {
    if (map.value.hasLayer(layers.value[layerName])) {
      map.value.removeLayer(layers.value[layerName])
    } else {
      map.value.addLayer(layers.value[layerName])
    }
  }
}

const zoomIn = () => {
  map.value.zoomIn()
}

const zoomOut = () => {
  map.value.zoomOut()
}

const resetView = () => {
  map.value.setView([0, 0], 2)
}

const clearMap = () => {
  // 清空所有图层
  Object.values(layers.value).forEach(layer => {
    layer.clearLayers()
  })
  
  // 清空数据
  mapElements.value = {
    rooms: [],
    npcs: [],
    items: [],
    fog: []
  }
  
  selectedElement.value = null
  ElMessage.success('地图已清空')
}

const saveMap = () => {
  // 保存地图数据到游戏状态
  const mapData = {
    rooms: mapElements.value.rooms.map(room => ({
      id: room.id,
      name: room.name,
      description: room.description,
      roomType: room.roomType,
      latlngs: room.latlngs
    })),
    npcs: mapElements.value.npcs.map(npc => ({
      id: npc.id,
      name: npc.name,
      description: npc.description,
      npcType: npc.npcType,
      latlng: npc.latlng
    })),
    items: mapElements.value.items.map(item => ({
      id: item.id,
      name: item.name,
      description: item.description,
      itemType: item.itemType,
      latlng: item.latlng
    })),
    fog: mapElements.value.fog.map(fog => ({
      id: fog.id,
      name: fog.name,
      description: fog.description,
      latlng: fog.latlng,
      radius: fog.radius
    }))
  }

  gameStore.mapData = mapData
  ElMessage.success('地图已保存')
}

// 生命周期
onMounted(async () => {
  await nextTick()
  initMap()
})

onUnmounted(() => {
  if (map.value) {
    map.value.remove()
  }
})
</script>

<style scoped>
.map-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
}

.header-right {
  display: flex;
  gap: 10px;
}

.editor-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.map-container {
  flex: 1;
  position: relative;
}

.map-canvas {
  width: 100%;
  height: 100%;
}

.map-toolbar {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1000;
}

.properties-panel {
  width: 300px;
  background: #f8f9fa;
  border-left: 1px solid #eee;
  overflow-y: auto;
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  color: #333;
}

.card-header .el-icon {
  color: #667eea;
}

.element-properties h4 {
  margin: 0 0 15px 0;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.no-selection {
  text-align: center;
  color: #999;
  padding: 20px;
}

.layer-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 地图标记样式 */
:deep(.npc-marker) {
  background: transparent;
  border: none;
  font-size: 20px;
}

:deep(.item-marker) {
  background: transparent;
  border: none;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .editor-content {
    flex-direction: column;
  }
  
  .properties-panel {
    width: 100%;
    height: 300px;
  }
  
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-right {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
